import {reqUserShopCart,reqDeleteShopCartInfo,reqChangeShopCheckedInfo} from "@/api";
const state = {
    cartlist:[]
};
const mutations = {
    GETCARTLIST(state,cartlist){
        state.cartlist = cartlist;
    }
};
const actions = {
    async getShopCartList({commit}) {
        let result = await reqUserShopCart();
        if(result.code == 200){
            commit('GETCARTLIST',result.data)
        }
    },
    async deleteShopCartInfo({commit},skuId) {
        let result = await reqDeleteShopCartInfo(skuId);
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    async ChangeShopCheckedInfo({commit},{skuId,isChecked}) {
        let result = await reqChangeShopCheckedInfo(skuId,isChecked);
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    //删除选中的商品信息
    deleteAllCertInfo({getters,dispatch}){
        let PromiseAll =[];
        getters.cartList.cartInfoList.forEach(item => {
            let promise =item.isChecked==1? dispatch('deleteShopCartInfo',item.skuId):'';
            PromiseAll.push(promise)
        });
        //只要全部的promise的返回值都为 成功，即都成功。
        return Promise.all(PromiseAll);
    },
    //点击全选键，可选中全部商品信息
    changeAllCertInfo({getters,dispatch},isChecked){
        console.log(isChecked)
        let PromiseAll =[];
        getters.cartList.cartInfoList.forEach(item => {
            let promise = dispatch('ChangeShopCheckedInfo',{skuId:item.skuId,isChecked});
            PromiseAll.push(promise)
        });
        //只要全部的promise的返回值都为 成功，即都成功。
        return Promise.all(PromiseAll);
    },
};
const getters = {
    cartList(state){
        return state.cartlist[0]||{}
    }
};
export default {
    state,
    mutations,
    actions,
    getters
}